package com.aipartner.controller;

import com.aipartner.common.Result;
import com.aipartner.dto.UploadExampleRequest;
import com.aipartner.service.UserUploadService;
import com.aipartner.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * 用户上传控制器
 */
@RestController
@RequestMapping("/api/user-upload")
public class UserUploadController {

    @Autowired
    private UserUploadService userUploadService;

    /**
     * 上传示例图片（通过图片URL）
     */
    @PostMapping("/example")
    public Result uploadExampleByUrl(@RequestBody @Valid UploadExampleRequest request) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("请先登录");
            }

            // 验证必填字段
            if (request.getTitle() == null || request.getTitle().trim().isEmpty()) {
                return Result.fail("请填写作品标题");
            }
            if (request.getPrompt() == null || request.getPrompt().trim().isEmpty()) {
                return Result.fail("请填写生成提示词");
            }
            if (request.getImageUrl() == null || request.getImageUrl().trim().isEmpty()) {
                return Result.fail("请提供图片URL");
            }

            request.setUserId(userId);
            request.setTitle(request.getTitle().trim());
            request.setPrompt(request.getPrompt().trim());
            request.setStyle(request.getStyle() != null ? request.getStyle().trim() : "");
            request.setSize(request.getSize() != null ? request.getSize().trim() : "");

            Long exampleId = userUploadService.uploadExampleByUrl(request);
            
            return Result.success(exampleId, "上传成功，作品已发布");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传示例图片（通过文件上传）
     */
    @PostMapping("/example/file")
    public Result uploadExampleByFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("prompt") String prompt,
            @RequestParam("style") String style,
            @RequestParam(value = "size", required = false) String size
    ) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("请先登录");
            }

            // 验证文件
            if (file.isEmpty()) {
                return Result.fail("请选择要上传的图片");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.fail("只能上传图片文件");
            }

            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.fail("图片大小不能超过5MB");
            }

            // 验证必填字段
            if (title == null || title.trim().isEmpty()) {
                return Result.fail("请填写作品标题");
            }
            if (prompt == null || prompt.trim().isEmpty()) {
                return Result.fail("请填写生成提示词");
            }

            UploadExampleRequest request = new UploadExampleRequest();
            request.setUserId(userId);
            request.setTitle(title.trim());
            request.setPrompt(prompt.trim());
            request.setStyle(style != null ? style.trim() : "");
            request.setSize(size != null ? size.trim() : "");

            Long recordId = userUploadService.uploadExample(file, request);
            
            return Result.success(recordId, "上传成功，请等待审核");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户上传记录
     */
    @GetMapping("/records")
    public Result getUserUploadRecords(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("请先登录");
            }

            return Result.success(userUploadService.getUserUploadRecords(userId, current, size));
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除上传记录
     */
    @DeleteMapping("/records/{recordId}")
    public Result deleteUploadRecord(@PathVariable Long recordId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("请先登录");
            }

            boolean success = userUploadService.deleteUploadRecord(recordId, userId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.fail("删除失败，记录不存在或无权限");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 点赞示例图片
     */
    @PostMapping("/like/{exampleId}")
    public Result likeExample(@PathVariable Long exampleId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("请先登录");
            }

            boolean liked = userUploadService.toggleLike(exampleId, userId);
            return Result.success(liked, liked ? "点赞成功" : "取消点赞");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("操作失败：" + e.getMessage());
        }
    }
}
